using MediatR;
using Microsoft.AspNetCore.Mvc;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.ErrorCode;

namespace S.M.SmartMedical.API.Read.Controllers
{
    /// <summary>
    /// 用户管理控制器（读操作）
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class UserController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<UserController> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mediator">中介者</param>
        /// <param name="logger">日志记录器</param>
        public UserController(IMediator mediator, ILogger<UserController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userLoginDto">用户登录信息</param>
        /// <returns>登录结果</returns>
        [HttpPost("login")]
        public async Task<APIResult<UserInfoDto>> Login([FromBody] UserLoginDto userLoginDto)
        {
            try
            {
                var query = new LoginUserQuery(userLoginDto);
                var result = await _mediator.Send(query);
                _logger.LogInformation("用户登录请求处理完成，用户名：{UserName}，结果：{Code}",
                    userLoginDto.UserName, result.Code);
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户登录接口异常，用户名：{UserName}", userLoginDto.UserName);
                return new APIResult<UserInfoDto>
                {
                    Code = APIEnum.Fail,
                    Message = "登录失败，系统异常",
                    Data = null!
                };
            }
        }
    }
}